package com.zdy.demo;

/**
 * @author deyou
 * @version 1.0
 * @date 2021/5/19 14:35
 */

public class SingletonPattern2 {

}

/**
 * 1. 饿汉式 线程安全，耗费资源
 */

class HugerSingleton1{
    private HugerSingleton1(){}
    //引入对象不可修改
    private static  final HugerSingleton1 instance = new HugerSingleton1();

    public static HugerSingleton1 getInstance(){
        return instance;
    }
}
/**
 * 2，饥饿式: 在静态代码块实例对象
 *
 */
class HugerSingleton2{
    private HugerSingleton2(){}
    private static  HugerSingleton2 instance;
    static {
        instance = new HugerSingleton2();
    }
    public static HugerSingleton2 getInstance(){
        return instance;
    }
}

/**
 * 3. 懒汉式， 非线程安全
 *
 */
class Singleton1{
    private Singleton1(){}
    private static Singleton1 instance;

    public static Singleton1 getInstance(){
        if (null == instance){
            instance = new Singleton1();
        }
        return instance;
    }
}
/**
 * 4. 线程安全懒汉式，给方法加锁
 *
 */
class Singleton2{
    private Singleton2(){}
    private static Singleton2 instance;

    public synchronized static Singleton2 getInstance() {
        if (null == instance){
            instance = new Singleton2();
        }
        return instance;
    }
}
/**
 * 5. 线程安全的懒汉式，双重检查锁(同步代码块）
 */
class Singleton3{
    private static Singleton3 instance;
    private Singleton3(){}

    public static Singleton3 getInstance() {
        if (null == instance){
            synchronized (Singleton3.class){
                if (null == instance){
                    instance = new Singleton3();
                }
            }
        }
        return instance;
    }
}

/**
 * 6. 线程安全的懒汉式 ： 静态内部类(推荐)
 */

class Singleton4{
   private static class innerClass{
       private static Singleton4 instance = new Singleton4();
   }
   private Singleton4(){}

    public static Singleton4 getInstance(){
       return  innerClass.instance;
    }
}
/**
 * 7. 线程安全的懒汉式,枚举
 */
enum Sinleton5{
    INSTANCE;

    public void whateverMethod(){
        //do Something
    }
}
